import { Router, Request, Response } from 'express';
import { VersionService } from '../services/VersionService';
import { ScriptService } from '../services/ScriptService';
import Joi from 'joi';

const router = Router();
const versionService = new VersionService();
const scriptService = new ScriptService();

// 验证中间件
const validateCreateVersion = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    script_id: Joi.string().uuid().required(),
    content: Joi.string().required(),
    message: Joi.string().max(500).optional(),
    author: Joi.string().max(255).optional(),
    parent_version: Joi.string().uuid().optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateVersionQuery = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    limit: Joi.number().integer().min(1).max(100).optional(),
    offset: Joi.number().integer().min(0).optional()
  });

  const { error } = schema.validate(req.query);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateCompareVersions = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    version_id_1: Joi.string().uuid().required(),
    version_id_2: Joi.string().uuid().required()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateRevertVersion = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    version_id: Joi.string().uuid().required(),
    message: Joi.string().max(500).optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateUpdateVersionMessage = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    message: Joi.string().max(500).required()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

// ==================== 版本管理核心功能 ====================

// 创建新版本
router.post('/', validateCreateVersion, async (req: Request, res: Response): Promise<void> => {
  try {
    const version = await versionService.createVersion(req.body);
    
    res.status(201).json({
      success: true,
      message: '版本创建成功',
      data: version
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '创建版本失败',
      error: error.message
    });
  }
});

// 获取脚本的版本历史
router.get('/scripts/:scriptId/history', validateVersionQuery, async (req: Request, res: Response): Promise<void> => {
  try {
    const { scriptId } = req.params;
    const { limit, offset } = req.query;
    
    const options: { limit?: number; offset?: number } = {};
    if (limit) options.limit = Number(limit);
    if (offset) options.offset = Number(offset);
    
    const result = await versionService.getVersionHistory(scriptId, options);
    
    res.json({
      success: true,
      message: '获取版本历史成功',
      data: result
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '获取版本历史失败',
      error: error.message
    });
  }
});

// 获取特定版本详情
router.get('/:versionId', async (req: Request, res: Response): Promise<void> => {
  try {
    const { versionId } = req.params;
    const version = await versionService.getVersionById(versionId);
    
    if (!version) {
      res.status(404).json({
        success: false,
        message: '版本不存在'
      });
      return;
    }
    
    res.json({
      success: true,
      message: '获取版本详情成功',
      data: version
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取版本详情失败',
      error: error.message
    });
  }
});

// 获取脚本的最新版本
router.get('/scripts/:scriptId/latest', async (req: Request, res: Response): Promise<void> => {
  try {
    const { scriptId } = req.params;
    const version = await versionService.getLatestVersion(scriptId);
    
    if (!version) {
      res.status(404).json({
        success: false,
        message: '脚本没有版本记录'
      });
      return;
    }
    
    res.json({
      success: true,
      message: '获取最新版本成功',
      data: version
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '获取最新版本失败',
      error: error.message
    });
  }
});

// ==================== 版本比较功能 ====================

// 比较两个版本的差异
router.post('/compare', validateCompareVersions, async (req: Request, res: Response): Promise<void> => {
  try {
    const { version_id_1, version_id_2 } = req.body;
    const result = await versionService.compareVersions(version_id_1, version_id_2);
    
    res.json({
      success: true,
      message: '版本比较成功',
      data: result
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '版本比较失败',
      error: error.message
    });
  }
});

// 获取版本内容预览
router.get('/:versionId/preview', async (req: Request, res: Response): Promise<void> => {
  try {
    const { versionId } = req.params;
    const { lines } = req.query;
    
    const result = await versionService.getVersionPreview(
      versionId, 
      lines ? Number(lines) : undefined
    );
    
    res.json({
      success: true,
      message: '获取版本预览成功',
      data: result
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '获取版本预览失败',
      error: error.message
    });
  }
});

// ==================== 版本回滚功能 ====================

// 回滚到指定版本
router.post('/scripts/:scriptId/revert', validateRevertVersion, async (req: Request, res: Response): Promise<void> => {
  try {
    const { scriptId } = req.params;
    const { version_id, message } = req.body;
    
    // 获取要回滚到的版本
    const targetVersion = await versionService.getVersionById(version_id);
    if (!targetVersion) {
      res.status(404).json({
        success: false,
        message: '目标版本不存在'
      });
      return;
    }
    
    if (targetVersion.script_id !== scriptId) {
      res.status(400).json({
        success: false,
        message: '版本不属于指定脚本'
      });
      return;
    }
    
    // 创建回滚版本（内容为目标版本的内容）
    const revertMessage = message || `回滚到版本 ${targetVersion.version}`;
    const createVersionData: any = {
      script_id: scriptId,
      content: targetVersion.content,
      message: revertMessage,
      author: req.body.author || 'system'
    };
    
    const newVersion = await versionService.createVersion(createVersionData);
    
    // 更新脚本内容
    await scriptService.updateScript(scriptId, {
      content: targetVersion.content
    });
    
    res.json({
      success: true,
      message: '版本回滚成功',
      data: {
        new_version: newVersion,
        reverted_to: targetVersion
      }
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '版本回滚失败',
      error: error.message
    });
  }
});

// ==================== 版本注释管理 ====================

// 更新版本注释
router.patch('/:versionId/message', validateUpdateVersionMessage, async (req: Request, res: Response): Promise<void> => {
  try {
    const { versionId } = req.params;
    const { message } = req.body;
    
    const version = await versionService.tagVersion(versionId, message);
    
    if (!version) {
      res.status(404).json({
        success: false,
        message: '版本不存在'
      });
      return;
    }
    
    res.json({
      success: true,
      message: '版本注释更新成功',
      data: version
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新版本注释失败',
      error: error.message
    });
  }
});

// ==================== 版本统计和分析 ====================

// 获取脚本版本统计信息
router.get('/scripts/:scriptId/stats', async (req: Request, res: Response): Promise<void> => {
  try {
    const { scriptId } = req.params;
    const stats = await versionService.getVersionStats(scriptId);
    
    res.json({
      success: true,
      message: '获取版本统计成功',
      data: stats
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '获取版本统计失败',
      error: error.message
    });
  }
});

// 获取版本树（显示版本关系）
router.get('/scripts/:scriptId/tree', async (req: Request, res: Response): Promise<void> => {
  try {
    const { scriptId } = req.params;
    const tree = await versionService.getVersionTree(scriptId);
    
    res.json({
      success: true,
      message: '获取版本树成功',
      data: tree
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '获取版本树失败',
      error: error.message
    });
  }
});

// 验证版本完整性
router.get('/scripts/:scriptId/validate', async (req: Request, res: Response): Promise<void> => {
  try {
    const { scriptId } = req.params;
    const validation = await versionService.validateVersionIntegrity(scriptId);
    
    res.json({
      success: true,
      message: '版本完整性验证完成',
      data: validation
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '版本完整性验证失败',
      error: error.message
    });
  }
});

// ==================== 版本管理操作 ====================

// 删除版本（仅允许删除最新版本）
router.delete('/:versionId', async (req: Request, res: Response): Promise<void> => {
  try {
    const { versionId } = req.params;
    const deleted = await versionService.deleteVersion(versionId);
    
    if (!deleted) {
      res.status(400).json({
        success: false,
        message: '删除版本失败'
      });
      return;
    }
    
    res.json({
      success: true,
      message: '版本删除成功'
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '删除版本失败',
      error: error.message
    });
  }
});

export default router;